<template>
  <div class="app-container">
    <div class="p4">
      <FaSearchBar :show-toggle="false">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="60px">
          <el-form-item label="表名" prop="tableName">
            <el-input v-model="queryParams.tableName" placeholder="请输入表名" clearable style="width: 150px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="描述" prop="tableComment">
            <el-input v-model="queryParams.tableComment" placeholder="请输入描述" clearable style="width: 150px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </FaSearchBar>
      <el-divider border-style="dashed" style="margin:0px 0px 20px 0px" />

      <el-space wrap>
        <el-button type="primary" icon="Download" @click="handleDownloadCode" v-auth="['gen$code']">生成</el-button>
        <el-button type="warning" icon="Upload" @click="openImportTable" v-auth="['gen$import']">导入</el-button>
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-auth="['gen$remove']">删除</el-button>

      </el-space>

      <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" stripe
        highlight-current-row border class="mt4">
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <!-- <el-table-column label="序号" type="index" width="60" align="center">
          <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
</el-table-column> -->
        <el-table-column label="表名" align="left" prop="tableName" :show-overflow-tooltip="true" width="150" />
        <el-table-column label="解释" align="left" prop="tableComment" :show-overflow-tooltip="true" width="150">
          <template #default="{ row }">
            <span v-if="!row.editing">{{ row.tableComment }}</span>
            <el-input v-else v-model="row.editData.tableComment" />
          </template>
        </el-table-column>
        <el-table-column label="包名" align="left" prop="packageName" :show-overflow-tooltip="true" width="150">
          <template #default="{ row }">
            <span v-if="!row.editing">{{ row.packageName }}</span>
            <el-input v-else v-model="row.editData.packageName" />
          </template>
        </el-table-column>
        <el-table-column label="类名" align="left" prop="className" :show-overflow-tooltip="true" width="150">
          <template #default="{ row }">
            <span v-if="!row.editing">{{ row.className }}</span>
            <el-input v-else v-model="row.editData.className" />
          </template>
        </el-table-column>
        <el-table-column label="上级菜单" align="left" prop="menuId" :show-overflow-tooltip="true" width="180">
          <template #default="{ row }">
            <span v-if="!row.editing">{{ row.menuId }}</span>

            <el-tree-select v-else v-model="row.editData.menuId" :data="menuOptions"
              :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id" placeholder="选择上级菜单"
              check-strictly :default-expanded-keys="[0]" />
          </template>
        </el-table-column>
        <el-table-column label="模块名称" align="left" prop="moduleName" width="150">
          <template #default="{ row }">
            <span v-if="!row.editing">{{ row.moduleName }}</span>
            <el-input v-else v-model="row.editData.moduleName" />
          </template>
        </el-table-column>
        <el-table-column label="控制器路径" align="left" prop="path" :show-overflow-tooltip="true" width="150">
          <template #default="{ row }">
            <span v-if="!row.editing">{{ row.path }}</span>
            <el-input v-else v-model="row.editData.path" />
          </template>
        </el-table-column>
        <el-table-column label="权限标识" align="left" prop="sign" :show-overflow-tooltip="true" width="120">
          <template #default="{ row }">
            <span v-if="!row.editing">{{ row.sign }}</span>
            <el-input v-else v-model="row.editData.sign" />
          </template>
        </el-table-column>
        <el-table-column label="实体基类" align="center" prop="baseClass" width="180">
          <template #default="{ row }">
            <span v-if="!row.editing">{{ row.baseClass }}</span>
            <el-select v-else v-model="row.editData.baseClass">
              <el-option label="BaseEntity" value="BaseEntity">
                <span style="float: left">基类</span>
                <span style="float: right; color: #8492a6; font-size: 13px">BaseEntity</span>
              </el-option>
              <el-option label="DefaultEntity" value="DefaultEntity">
                <span style="float: left">默认基类</span>
                <span style="float: right; color: #8492a6; font-size: 13px">DefaultEntity</span>
              </el-option>
              <el-option label="LogicDeleteEntity" value="LogicDeleteEntity">
                <span style="float: left">逻辑删除</span>
                <span style="float: right; color: #8492a6; font-size: 13px">LogicDeleteEntity</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <!-- <el-table-column label="上下文路径" align="left" prop="contextPath" :show-overflow-tooltip="true" width="120" />
        <el-table-column label="作者" align="left" prop="author" :show-overflow-tooltip="true" width="120" /> -->
        <el-table-column label="更新时间" align="center" prop="updatedAt" width="200" />
        <el-table-column label="" class-name="small-padding fixed-width" width="260" fixed="right">
          <template #default="{ row, $index }">
            <div class="row-box" style="display: flex; flex-direction: row; align-items: center">
              <div v-if="!row.editing">
                <el-button size="small" plain icon="View" @click="handlePreview(row)" v-auth="['gen$preview']">
                  预览
                </el-button>
                <el-button size="small" plain icon="Download" @click="handleDownloadCode(row)" v-auth="['gen$preview']"
                  style="margin-right: 10px;">
                  生成
                </el-button>
                <el-dropdown trigger="click" v-auth="['gen$edit', 'gen$code', 'gen$remove']">
                  <el-button size="small" plain>更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-auth="['gen$edit']" @click="handleSynchTable(row)">
                        <el-icon :size="size" :color="color">
                          <Refresh />
                        </el-icon>同步
                      </el-dropdown-item>
                      <el-dropdown-item v-auth="['gen$code']" @click="handleField(row)">
                        <el-icon :size="size" :color="color">
                          <Tickets />
                        </el-icon>字段</el-dropdown-item>
                      <el-dropdown-item v-auth="['gen$edit']" @click="handleEdit(row)">
                        <el-icon :size="size" :color="color">
                          <Edit />
                        </el-icon>修改</el-dropdown-item>
                      <el-dropdown-item divided v-auth="['gen$remove']" @click="handleDelete(row, $index)">
                        <el-icon :size="size" :color="color">
                          <Delete />
                        </el-icon>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div v-else>
                <el-button size="small" type="success" @click="handleSave(row, $index)">保存</el-button>
                <el-button size="small" @click="handleCancel(row, $index)">取消</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </div>
    <!-- 预览界面 -->
    <el-dialog :title="preview.title" v-model="preview.open" width="80%" top="5vh" append-to-body
      custom-class="scrollbar">
      <el-tabs v-model="preview.activeName" tab-position="left">
        <el-tab-pane v-for="item in preview.data" :label="item.ftl" :name="item.ftl">
          <ShikiCode :code="item.code" :language="item.language" />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <import-table ref="importRef" @ok="handleQuery" />
    <field ref="fieldRef" />
  </div>
</template>

<script setup name="Gen">
import apiTable from "@/api/tool/genTable";
import router from "@/router"
import importTable from "./importTable.vue"
import field from "./field.vue"
import ShikiCode from '@/components/ShikiCode/index.vue'
import apiMenu from "@/api/system/menu";


const route = useRoute();
const { proxy } = getCurrentInstance();

const tableList = ref([]);
const loading = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const tableNames = ref([]);
const uniqueId = ref("");

const menuOptions = ref([]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tableName: undefined,
    tableComment: undefined
  },
  preview: {
    open: false,
    title: "代码预览",
    data: {},
    activeName: "Entity.java"
  },
  setupField: {
    open: false,
    title: "字段管理"
  }
});

const { queryParams, preview, setupField } = toRefs(data);

onActivated(() => {
  const time = route.query.t;
  if (time != null && time != uniqueId.value) {
    uniqueId.value = time;
    queryParams.value.pageNum = Number(route.query.pageNum);
    proxy.resetForm("queryForm");
    getList();
  }
})

/** 查询表集合 */
function getList() {
  // loading.value = true;
  apiTable.page(queryParams.value).then(response => {
    tableList.value = response.data.rows;
    total.value = response.data.total;
  }).finally(() => {
    loading.value = false
  })
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 生成代码操作 */
function handleDownloadCode(row) {
  const tableIds = row.id || ids.value;
  const tbNames = row.tableName || tableNames.value;
  if (tableIds == "" || tableIds.length == 0) {
    proxy.$modal.error("请选择要生成的数据");
    return;
  }
  proxy.$download.zip("/admin/generator/table/download?ids=" + tableIds, tbNames + ".src.zip");
}
/** 同步数据库操作 */
function handleSynchTable(row) {
  proxy.$modal.confirm('确认要强制同步"' + row.tableName + '"表结构吗？').then(function () {
    return apiTable.synchDbTable(row.id);
  }).then(() => {
    proxy.$modal.success("同步成功");
  }).catch(() => { });
}
/** 打开导入表弹窗 */
function openImportTable() {
  proxy.$refs["importRef"].show();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 预览按钮 */
function handlePreview(row) {
  apiTable.previewCode(row.id).then(response => {
    preview.value.data = response.data;
    preview.value.open = true;
    preview.value.activeName = "Entity.java";
  });
}
/** 字段 */
function handleField(row) {
  proxy.$refs["fieldRef"].show(row);
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  tableNames.value = selection.map(item => item.tableName);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 编辑行
const handleEdit = (row, index) => {
  // 先取消其他行的编辑状态
  tableList.value.forEach(item => {
    if (item.editing) {
      item.editing = false
    }
  })
  // 设置当前行编辑状态
  row.editing = true
  // 备份原始数据
  row.editData = { ...row }
}


// 保存行
const handleSave = (row, index) => {
  // 更新数据
  Object.keys(row.editData).forEach(key => {
    if (key !== 'editing' && key !== 'editData') {
      row[key] = row.editData[key]
    }
  })
  apiTable.update({
    id: row.id,
    tableComment: row.editData.tableComment,
    packageName: row.editData.packageName,
    className: row.editData.className,
    moduleName: row.editData.moduleName,
    path: row.editData.path,
    sign: row.editData.sign,
    menuId: row.editData.menuId,
    baseClass: row.editData.baseClass
  }).then(res => {
    proxy.$message.success("更新成功");
    // 退出编辑状态
    row.editing = false
    // 清空临时数据
    row.editData = {}
  }).catch(err => {
    proxy.$message.error(err.message);
  });
}

// 取消编辑
const handleCancel = (row, index) => {
  // 退出编辑状态
  row.editing = false
  // 清空临时数据
  row.editData = {}
}

/** 删除按钮操作 */
function handleDelete(row) {
  const tableIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除表编号为"' + tableIds + '"的数据项？').then(function () {
    return apiTable.delete(tableIds);
  }).then(() => {
    getList();
    proxy.$modal.success("删除成功");
  }).catch(() => { });
}

/** 查询菜单下拉树结构 */
function getTreeselect() {
  menuOptions.value = [];
  apiMenu.list().then(response => {
    const menu = { id: 0, name: "主板块", children: [] };
    menu.children = proxy.handleTree(response.data, "id");
    menuOptions.value.push(menu);
  });
}

getTreeselect()
getList();
</script>
